package com.sgb.jicai.view.fragment;


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.sgb.jicai.R;
import com.sgb.jicai.base.JiCaiBaseApi;
import com.sgb.jicai.databinding.FragmentMycenterMyJoinFactoryBinding;
import com.sgb.jicai.entity.JcMyJoinFactoryListEntity;
import com.sgb.jicai.event.JiCaiEventEntity;
import com.sgb.jicai.view.activity.MyCenterMyJoinActivity;
import com.sgb.jicai.view.adapter.CenterMyJoinFactoryAdapter;
import com.sgb.jicai.viewmodel.CentralizedMining5Model;
import com.sgb.jicai.viewmodel.MyCenterMyJoinFactoryFraModel;
import com.sgb.link.entity.EventConstant;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.xrecyclerview.XRecyclerView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;

/**
 * 个人中心--我的加盟--供方发起fragment
 */
public class MyCenterMyJoinFactoryFragment extends AppLazyFragment {

    MyCenterMyJoinFactoryFraModel viewModel;
    FragmentMycenterMyJoinFactoryBinding binding;

    //厂家集采
    private String method;
    public static final String JICAI_METHOD = "JiCaiMethod";
    //二级标题：全部、集采中…………
    private String state;
    public static final String JICAI_STATE = "JiCaiState";

    private CenterMyJoinFactoryAdapter adapter;
    private String keyWords = "";//搜索关键词

    public static MyCenterMyJoinFactoryFragment newInstance(String jicaiMethod, String jicaiState) {
        MyCenterMyJoinFactoryFragment fragment = new MyCenterMyJoinFactoryFragment();
        Bundle bundle = new Bundle();
        bundle.putString(JICAI_METHOD, jicaiMethod);
        bundle.putString(JICAI_STATE, jicaiState);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_mycenter_my_join_factory, container, false);
        viewModel = new ViewModelProvider(this).get(MyCenterMyJoinFactoryFraModel.class);
        viewModel.setActivity(MyCenterMyJoinFactoryFragment.this);
        if (getArguments() != null) {
            //获取传递过来的值
            method = getArguments().getString(JICAI_METHOD);
            state = getArguments().getString(JICAI_STATE);
        }
        return binding.getRoot();
    }

    @Override
    protected void initView() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        if (adapter == null) {
            adapter = new CenterMyJoinFactoryAdapter(getActivity(), null);
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        //binding.recyclerView.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0, getActivity().getResources().getDimension(R.dimen.dp1), getActivity().getResources().getColor(R.color.color_F5F5F5)));
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                viewModel.getList(state, keyWords, false);
            }

            @Override
            public void onLoadMore() {
                if (viewModel.hasNext) {
                    viewModel.getList(state, keyWords, true);
                } else {
                    binding.recyclerView.loadMoreComplete();
                }

            }
        });
        binding.recyclerView.setAdapter(adapter);

        adapter.setOnItemClick(new AdapterOnItemClick<JcMyJoinFactoryListEntity>() {
            @Override
            public void onItemClick(JcMyJoinFactoryListEntity entity, int position) {
                viewModel.getH5Url(entity);
            }
        });


        adapter.setExitListerner(new CenterMyJoinFactoryAdapter.ExitListerner() {
            @Override
            public void quitJc(JcMyJoinFactoryListEntity entity) {
                String msg = "您确认退出此次集采？";
                new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                        .setTitle("温馨提示")
                        .setMsg(msg)
                        .setDialogCallBack(new CommonDialog.DialogCallBack() {
                            @Override
                            public void onRightClick() {
                                //退出集采
                                viewModel.quitJiCai(entity.getOrderNo());
                            }

                            @Override
                            public void onLeftClick() {
                            }
                        }).show();
            }

            @Override
            public void DeleteJc(JcMyJoinFactoryListEntity entity) {
                String msg = "将永久删除该条数，还要继续吗？";
                new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                        .setTitle("温馨提示")
                        .setMsg(msg)
                        .setDialogCallBack(new CommonDialog.DialogCallBack() {
                            @Override
                            public void onRightClick() {
                                viewModel.deleteJoin(entity.getOrderNo());
                            }

                            @Override
                            public void onLeftClick() {

                            }
                        }).show();
            }
        });

        binding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {//SCROLL_STATE_IDLE:停止滚动
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (layoutManager.findFirstVisibleItemPosition() > 1) {
                    binding.imgBackTop.setVisibility(View.VISIBLE);
                } else {
                    binding.imgBackTop.setVisibility(View.GONE);
                }
            }
        });
        binding.imgBackTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.recyclerView.scrollToPosition(0);
                EventBus.getDefault().post(new JiCaiEventEntity(EventConstant.EVENT_JICAI_TOP_REFRESH_VISIBLE, ""));
            }
        });
    }

    @Override
    protected void onLazyLoad() {
        initData();
    }

    public void initData() {
        if (getActivity() instanceof MyCenterMyJoinActivity){
            keyWords = ((MyCenterMyJoinActivity)getActivity()).getKeyWords();
        }
        viewModel.getList(state, keyWords, false);
    }

    public void showList(List<JcMyJoinFactoryListEntity> list, boolean isLoadMore, boolean hasNext) {

        if (list == null) list = new ArrayList<>();
        binding.recyclerView.refreshComplete();
        binding.recyclerView.loadMoreComplete();
        if (isLoadMore) {
            if (list.size() != 0) {
                adapter.addDatas(list);
            }else {
                binding.recyclerView.setNoMore(true);
            }
        } else {
            if (list.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
                binding.imgBackTop.setVisibility(View.GONE);
            } else {
                binding.emptyView.setVisibility(View.GONE);
            }
            adapter.clearDatas();
            binding.recyclerView.setLoadingMoreEnabled(true);
            adapter.setDatas(list);
            binding.recyclerView.setNoMore(false);
        }
        if (adapter.getItemCount() >= 3) {
            binding.recyclerView.setNoMore(!viewModel.hasNext);
        } else {
            binding.recyclerView.setLoadingMoreEnabled(viewModel.hasNext);
        }
        ((MyCenterMyJoinActivity)getActivity()).getTabNum();
    }

    public void showUrl(String url) {
        JiCaiBaseApi.startWeb(getActivity(), url);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(JiCaiEventEntity event) {
        if (event.getCode() == EventConstant.EVENT_JICAI_MY_CEN_AND_JOIN) {
            keyWords = event.getName();
            initData();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
